<?php
/**
 * (ajax) 平台产品
 */
namespace App\Admin\Ajax\Products;

use App\Models\Product\ProductPlatSku;
use Illuminate\Support\Facades\DB;

class PlatSkuAjax{

    /**
     * 停用
     * @param $ids
     * @return \Illuminate\Http\JsonResponse
     */
    public function disableItem($ids){
        try{
            $collection = ProductPlatSku::query()->findMany($ids);
            $count = 0;
            foreach ($collection as $model) {
                DB::beginTransaction();
                if($model->status == 2){
                    DB::rollBack();
                    continue;
                }
                $model->status = 2;
                if($model->times != 0){
                    $model->times = 0;
                }
                $flag = $model->save();
                if(!$flag){
                    DB::rollBack();
                }else{
                    $count++;
                    DB::commit();
                }
            }
            return response()->json(['status' => true, 'message' => "成功停用{$count}条记录！"]);
        }catch (\Exception $e){
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    /**
     * 启用
     * @param $ids
     * @return \Illuminate\Http\JsonResponse
     */
    public function enableItem($ids){
        try{
            $collection = ProductPlatSku::query()->findMany($ids);
            $count = 0;
            $items = [];
            foreach ($collection as $model) {
                DB::beginTransaction();
                if($model->status == 1){
                    DB::rollBack();
                    continue;
                }
                $model->status = 1;
                $flag = $model->save();
                if(!$flag){
                    DB::rollBack();
                }else{
                    $count++;
                    DB::commit();
                    if($model->fan_eu == 1){
                        $fanEuKey = $model->seller_sku.'_'.$model->child_asin.'_'.$model->fnsku;
                        if(!in_array($fanEuKey,$items)){
                            $items[] = $fanEuKey;
                        }
                    }
                }
            }

            /*
            //同平台产品一样,暂不确定产品是否需要同步关系？ (功能暂用)
            if(!empty($items)){
                AmazonSkuUpRelate::dispatch($items);
            }*/

            return response()->json(['status' => true, 'message' => "成功启用{$count}条记录！"]);
        }catch (\Exception $e){
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

}
